//
//  WeiboManager.m
//  TecentDemo
//
//  Created by leo on 9/14/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "WeiboManager.h"
#import "NSURL+QAdditions.h"
#import "QOauthKey.h"
#import "QWeiboRequest.h"
#import "NSURL+QAdditions.h"
#import "Model.h"
#import "AdapterHelp.h"
#import "QSyncHttp.h"
#import "JsonStatusParser.h"
#import "InvalidParameterException.h"


#define AppKey			@"weiboAppKey"
#define AppSecret		@"weiboAppSecret"
#define AppTokenKey		@"weiboTokenKey"
#define AppTokenSecret	@"weiboTokenSecret"
static WeiboManager *weiboManager=nil;

@implementation WeiboManager

NSString * baseUrl = @"http://api.t.sina.com.cn/";
NSString * error = @"error_code";
#pragma ManagerDelegat

- (void)parseTokenKeyWithResponse:(NSString *)aResponse
{
	
	NSDictionary *params = [NSURL parseURLQueryString:aResponse];
	self.tokenKey = [params objectForKey:@"oauth_token"];
	self.tokenSecret = [params objectForKey:@"oauth_token_secret"];
  //   self.userid = [params objectForKey:@"userid"];
	
}

- (void)saveDefaultKey {
	
	[[NSUserDefaults standardUserDefaults] setValue:self.appKey forKey:AppKey];
	[[NSUserDefaults standardUserDefaults] setValue:self.appSecret forKey:AppSecret];
	[[NSUserDefaults standardUserDefaults] setValue:self.tokenKey forKey:AppTokenKey];
	[[NSUserDefaults standardUserDefaults] setValue:self.tokenSecret forKey:AppTokenSecret];
	[[NSUserDefaults standardUserDefaults] synchronize];
}


- (void)loadDefaultKey
{
    self.appKey = [[NSUserDefaults standardUserDefaults] valueForKey:AppKey];
	self.appSecret = [[NSUserDefaults standardUserDefaults] valueForKey:AppSecret];
	self.tokenKey = [[NSUserDefaults standardUserDefaults] valueForKey:AppTokenKey];
	self.tokenSecret = [[NSUserDefaults standardUserDefaults] valueForKey:AppTokenSecret];

}


#pragma init

-(id)initwithDefault
{
    self = [super init];
    
    if (self) {
        self.VERIFY_URL = @"http://api.t.sina.com.cn/oauth/authorize?oauth_token=";
        self.appKey = @"2987189012";
        self.appSecret = @"c5538f15f2a000179d851119debf36b1";
        self.acces_token_url = @"http://api.t.sina.com.cn/oauth/access_token";
        self.request_token_url = @"http://api.t.sina.com.cn/oauth/request_token";
    }
    return self; 
    
}





+ (id)instance
{
  
  if(nil==weiboManager)
  {

      weiboManager =[[WeiboManager alloc]initwithDefault];
  }
    return weiboManager;
}

// public get msg
- (NSArray *)getHomeMsgWithPageFlage:(PageFlag)aPageFlag 
                             nReqNum:(NSInteger)aReqNum{
    
    NSArray *result = [self getFriendsTimeline:0 maxId:nil count:aReqNum page:aPageFlag];
    return result;
}


//private

//get status
//getFriendsTimeline
- (NSArray *)getFriendsTimeline:(long) sinceId 
                          maxId:(long) maxid 
                          count:(int) maxCount 
                           page:(int) currentPage{
	NSMutableString * url = [[NSMutableString alloc] init];
	[url appendString:baseUrl];
    [url appendFormat:@"statuses/friends_timeline.json"];
	NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
	[parameters setObject:[NSString stringWithFormat:@"%d", sinceId] forKey:@"since_id"];
    [parameters setObject:[NSString stringWithFormat:@"%d", maxCount] forKey:@"count"];
    [parameters setObject:[NSString stringWithFormat:@"%d", currentPage] forKey:@"page"];
    [parameters setObject:[NSString stringWithFormat:@"%d", maxid] forKey:@"max_id"];
    
	QWeiboRequest *request = [[QWeiboRequest alloc] init];
    QOauthKey *oauthKey = [self getOauthKey];
	NSString *retString = [request syncRequestWithUrl:url httpMethod:@"POST" oauthKey:oauthKey parameters:parameters files:nil];
    // NSLog(@"=========%@",retString);
    NSArray * result = [JsonStatusParser parseToStatuses:retString];
    [url release];
 	[request release];
	[result autorelease];
	return result;
    
}


- (NSArray *)getPublicTimeline:(int) count{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/public_timeline.json"];
	
	NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
	[parameters setObject:[NSString stringWithFormat:@"%d", count] forKey:@"count"];
    
	QWeiboRequest *request = [[QWeiboRequest alloc] init];
    QOauthKey *oauthKey = [self getOauthKey];
	NSString *retString = [request syncRequestWithUrl:urlString 
                                           httpMethod:@"POST" 
                                             oauthKey:oauthKey 
                                           parameters:parameters 
                                                files:nil];
    NSArray * result = [JsonStatusParser parseToStatuses:retString];
 	[request release];
	[result autorelease];
	return result;
}


- (NSArray *)getUserTimeline:(long) uid 
                      userId:(int) userId 
                  screenName:(NSString *) screenName 
                     sinceId:(long) sinceId
                       maxId:(long) maxid 
                       count:(int) maxCount 
                        page:(int) currentPage{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	// uid will lost at here temporarily
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:[NSString stringWithFormat:@"%lld",userId] forKey:@"user_id"];
	[parameters setObject:[NSString stringWithFormat:@"%lld", sinceId] forKey:@"since_id"];
    [parameters setObject:[NSString stringWithFormat:@"%lld",maxid] forKey:@"max_id"];
    [parameters setObject:[NSString stringWithFormat:@"%d",maxCount] forKey:@"count"];
    [parameters setObject:[NSString stringWithFormat:@"%d",currentPage] forKey:@"page"];
    
	QWeiboRequest *request = [[QWeiboRequest alloc] init];
    QOauthKey *oauthKey = [self getOauthKey];
	NSString *retString = [request syncRequestWithUrl:urlString 
                                           httpMethod:@"POST" 
                                             oauthKey:oauthKey 
                                           parameters:parameters 
                                                files:nil];
    NSArray * result = [JsonStatusParser parseToStatuses:retString];
 	[request release];
	[result autorelease];
	return result;
}

- (NSArray *)getMentions:(long) sinceId
                   maxId:(long) maxid 
                   count:(int) maxCount 
                    page:(int) currentPage{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/mentions.json"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
	[parameters setObject:[NSString stringWithFormat:@"%lld", sinceId] forKey:@"since_id"];
    [parameters setObject:[NSString stringWithFormat:@"%lld",maxid] forKey:@"max_id"];
    [parameters setObject:[NSString stringWithFormat:@"%d",maxCount] forKey:@"count"];
    [parameters setObject:[NSString stringWithFormat:@"%d",currentPage] forKey:@"page"];
    QWeiboRequest *request = [[QWeiboRequest alloc] init];
    QOauthKey *oauthKey = [self getOauthKey];
	NSString *retString = [request syncRequestWithUrl:urlString 
                                           httpMethod:@"POST" 
                                             oauthKey:oauthKey 
                                           parameters:parameters 
                                                files:nil];
    NSArray * result = [JsonStatusParser parseToStatuses:retString];
 	[request release];
	[result autorelease];
	return result;		
}

- (NSArray *)getCommentsTimeline:(long) sinceId 
                           maxId:(long) maxid 
                           count:(int) maxCount 
                            page:(int) currentPage{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/comments_timeline.json"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
	[parameters setObject:[NSString stringWithFormat:@"%lld", sinceId] forKey:@"since_id"];
    [parameters setObject:[NSString stringWithFormat:@"%lld",maxid] forKey:@"max_id"];
    [parameters setObject:[NSString stringWithFormat:@"%d",maxCount] forKey:@"count"];
    [parameters setObject:[NSString stringWithFormat:@"%d",currentPage] forKey:@"page"];
    
	QWeiboRequest *request = [[QWeiboRequest alloc] init];
    QOauthKey *oauthKey = [self getOauthKey];
	NSString *retString = [request syncRequestWithUrl:urlString 
                                           httpMethod:@"POST" 
                                             oauthKey:oauthKey 
                                           parameters:parameters 
                                                files:nil];
    NSArray * result = [JsonStatusParser parseToStatuses:retString];
 	[request release];
	[result autorelease];
	return result;	
}

- (NSArray *)getCommentsByMe:(long) sinceId 
                       maxId:(long) maxid 
                       count:(int) maxCount 
                        page:(int) currentPage{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/comments_by_me.json"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
	[parameters setObject:[NSString stringWithFormat:@"%lld", sinceId] forKey:@"since_id"];
    [parameters setObject:[NSString stringWithFormat:@"%lld",maxid] forKey:@"max_id"];
    [parameters setObject:[NSString stringWithFormat:@"%d",maxCount] forKey:@"count"];
    [parameters setObject:[NSString stringWithFormat:@"%d",currentPage] forKey:@"page"];
    
	QWeiboRequest *request = [[QWeiboRequest alloc] init];
    QOauthKey *oauthKey = [self getOauthKey];
	NSString *retString = [request syncRequestWithUrl:urlString 
                                           httpMethod:@"POST" 
                                             oauthKey:oauthKey 
                                           parameters:parameters 
                                                files:nil];
    NSArray * result = [JsonStatusParser parseToStatuses:retString];
 	[request release];
	[result autorelease];
	return result;			
}

- (NSArray *)getCommentsToMe:(long) sinceId 
                       maxId:(long) maxid 
                       count:(int) maxCount 
                        page:(int) currentPage{
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/comments_to_me.json"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
	[parameters setObject:[NSString stringWithFormat:@"%lld", sinceId] forKey:@"since_id"];
    [parameters setObject:[NSString stringWithFormat:@"%lld",maxid] forKey:@"max_id"];
    [parameters setObject:[NSString stringWithFormat:@"%d",maxCount] forKey:@"count"];
    [parameters setObject:[NSString stringWithFormat:@"%d",currentPage] forKey:@"page"];
    
	QWeiboRequest *request = [[QWeiboRequest alloc] init];
    QOauthKey *oauthKey = [self getOauthKey];
	NSString *retString = [request syncRequestWithUrl:urlString 
                                           httpMethod:@"POST" 
                                             oauthKey:oauthKey 
                                           parameters:parameters 
                                                files:nil];
    NSArray * result = [JsonStatusParser parseToStatuses:retString];
 	[request release];
	[result autorelease];
	return result;		
}

- (NSArray *)getComments:(long) statusId count:(int) maxCount page:(int) currentPage{
    
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/comments.json"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
	[parameters setObject:[NSString stringWithFormat:@"%lld", statusId] forKey:@"id"];
    [parameters setObject:[NSString stringWithFormat:@"%d",maxCount] forKey:@"count"];
    [parameters setObject:[NSString stringWithFormat:@"%d",currentPage] forKey:@"page"];
    
	QWeiboRequest *request = [[QWeiboRequest alloc] init];
    QOauthKey *oauthKey = [self getOauthKey];
	NSString *retString = [request syncRequestWithUrl:urlString 
                                           httpMethod:@"POST" 
                                             oauthKey:oauthKey 
                                           parameters:parameters 
                                                files:nil];
    NSArray * result = [JsonStatusParser parseToStatuses:retString];
 	[request release];
	[result autorelease];
	return result;		


}

//status

//- (Status *)statusUpdate:(NSString *) status 
//       inReplyToStatusId:(long) replyToId 
//                latitude:(double) lat 
//               longitude:(double) longitude{
//    if(status == nil){
//		InvalidParameterException * exception = [InvalidParameterException 
//												 exceptionWithName:@"Invalid Parameter Exception" reason:@"Status should not be nil. " userInfo:nil];
//		@throw exception;
//	}
//    NSMutableString * urlString = [[NSMutableString alloc] init];
//	[urlString appendString:baseUrl];
//	[urlString appendFormat:@"statuses/update.json"];
//	NSMutableDictionary * mbody = [[NSMutableDictionary alloc] init];
//	[mbody setObject:status forKey:@"status"];
//	if(replyToId!=nilReplyId)
//        [self generateBodyDic:mbody paraKey:@"in_reply_to_status_id" paraValue:[NSString stringWithFormat:@"%llu",replyToId]];
//	if(lat != nilLatitude)
//        [self generateBodyDic:mbody paraKey:@"lat" paraValue:[NSString stringWithFormat:@"%f",lat] ];
//	if(longitude != nilLongitude)
//        [self generateBodyDic:mbody paraKey:@"long" paraValue:[NSString stringWithFormat:@"%f",longitude] ];
//	NSString * resultString = [self retrieveData:urlString callMethod: POST body:mbody];
//	NSRange range = [resultString rangeOfString:error];
//	if(range.location == NSNotFound){
//		Status * result = [JsonStatusParser parseToStatus:resultString];
//		[urlString release];
//		[result autorelease];
//		[resultString release];
//		[mbody release];
//		return result;	
//	}else{
//		ServerSideException * exception = [[[ServerSideException alloc] init] autorelease];
//		ServerSideError * errorMsg = [JsonStatusParser parsetoServerSideError:resultString];
//		[exception setError:errorMsg];
//		[errorMsg release];
//		[urlString release];
//		[resultString release];
//		[mbody release];
//		@throw exception;
//	}
//}

//- (Status *)statusUpload:(NSString *) status
//                     pic:(NSString *) pic 
//                latitude:(double ) latitude 
//               longitude:(double) longitude{
//	if(status == nil||pic == nil){
//        InvalidParameterException * exception = [InvalidParameterException 
//												 exceptionWithName:@"Invalid Parameter Exception" reason:@"Status should not be nil. " userInfo:nil];
//		@throw exception;	
//	}
//    
//    
//    
//	NSMutableString * urlString = [[NSMutableString alloc] init];
//	[urlString appendString:baseUrl];
//	[urlString appendFormat:@"statuses/upload.json"];
// 
//    pic = [pic stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//	NSURL * picUrl = [NSURL URLWithString:pic];
//    NSMutableDictionary *paraDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:status,@"status", nil];
//	FilePart * picPart = [[FilePart alloc] initWithNameAndFile:@"pic" file:picUrl];
//	[method addPart:statusPart];
//	[method addPart:picPart];
//	if(lat != nilLatitude){
//		StringPart * latPart = [[StringPart alloc] initWithParameter:[[[NSString alloc] initWithFormat:@"%f",lat] autorelease] withName:@"latitude"];
//        [paraDic setValue:[[NSString alloc] initWithFormat:@"%f",lat] forKey:@"lat"];
//		[method addPart:latPart];
//		[latPart release];
//	}
//	if(log != nilLongitude){
//		StringPart * logPart = [[StringPart alloc] initWithParameter:[[[NSString alloc] initWithFormat:@"%f",log] autorelease] withName:@"longitude"];
//        [paraDic setValue:[[NSString alloc] initWithFormat:@"%f",log] forKey:@"long"];
//		[method addPart:logPart];
//		[logPart release];
//	}	
//    
//	NSString * resultString = [self uploadData:status url:urlString picture:pic lat:latitude log:longitude];
//	NSRange range = [resultString rangeOfString:error];
//	if(range.location == NSNotFound){
//		Status * result = [JsonStatusParser parseToStatus:resultString];
//		[urlString release];
//		[result autorelease];
//		[resultString release];
//		return result;	
//	}else{
//		ServerSideException * exception = [[[ServerSideException alloc] init] autorelease];
//		ServerSideError * errorMsg = [JsonStatusParser parsetoServerSideError:resultString];
//		[exception setError:errorMsg];
//		[errorMsg release];
//		[urlString release];
//		[resultString release];
//		@throw exception;
//	}
//}


- (Status *)statusDestroy:(long) statusId{
	if(statusId<0){
		InvalidParameterException * exception = [InvalidParameterException 
												 exceptionWithName:@"Invalid Parameter Exception" reason:@"Status should not be nil. " userInfo:nil];
		@throw exception;		
	}
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/destroy/%lld.json",statusId];
	QWeiboRequest *request = [[QWeiboRequest alloc] init];
    QOauthKey *oauthKey = [self getOauthKey];
	NSString *retString = [request syncRequestWithUrl:urlString 
                                           httpMethod:@"POST" 
                                             oauthKey:oauthKey 
                                           parameters:nil 
                                                files:nil];
    
	Status * result = [JsonStatusParser parseToStatus:retString];
	[urlString release];
	[result autorelease];
	[retString release];
	return result;							
}

- (Status *)statusRepost:(long) statusId 
                  status:(NSString *) status 
             withComment:(int) withComment{
	if(status == nil||statusId<=0){
		InvalidParameterException * exception = [InvalidParameterException 
												 exceptionWithName:@"Invalid Parameter Exception" reason:@"Status should not be nil. " userInfo:nil];
		@throw exception;
	}
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/repost.json"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
	[parameters setObject:[NSString stringWithFormat:@"%lld", statusId] forKey:@"id"];
    [parameters setObject:status forKey:@"status"];
    [parameters setObject:[NSString stringWithFormat:@"%d",withComment] forKey:@"is_comment"];
    
	QWeiboRequest *request = [[QWeiboRequest alloc] init];
    QOauthKey *oauthKey = [self getOauthKey];
	NSString *retString = [request syncRequestWithUrl:urlString 
                                           httpMethod:@"POST" 
                                             oauthKey:oauthKey 
                                           parameters:parameters 
                                                files:nil];

	Status * result = [JsonStatusParser parseToStatus:retString];
	[urlString release];
	[result autorelease];
	[retString release];
	return result;	
}


//comment

- (Comment *)comment:(long) statusId 
       commentString:(NSString *) commentString{
	if(statusId == NULL||commentString==nil){
		InvalidParameterException * exception = [InvalidParameterException 
												 exceptionWithName:@"Invalid Parameter Exception" reason:@"Status should not be nil. " userInfo:nil];
		@throw exception;
	}
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/comment.json"];
	
	 NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
	[parameters setObject:[NSString stringWithFormat:@"%lld", statusId] forKey:@"id"];
    [parameters setObject:commentString forKey:@"comment"];
     
	QWeiboRequest *request = [[QWeiboRequest alloc] init];
    QOauthKey *oauthKey = [self getOauthKey];
	NSString *retString = [request syncRequestWithUrl:urlString 
                                           httpMethod:@"POST" 
                                             oauthKey:oauthKey 
                                           parameters:parameters 
                                                files:nil];
	Comment * result = [JsonStatusParser parseToComment:retString];
    
	[urlString release];
	[result autorelease];
	[retString release];
	return result;					
}


- (Comment *)commentDestroy:(long) commentId{
	if(commentId<=0){
		InvalidParameterException * exception = [InvalidParameterException 
												 exceptionWithName:@"Invalid Parameter Exception" reason:@"Status should not be nil. " userInfo:nil];
		@throw exception;		
	}
	NSMutableString * urlString = [[NSMutableString alloc] init];
	[urlString appendString:baseUrl];
	[urlString appendFormat:@"statuses/comment_destroy/%lf.json",commentId];
	QWeiboRequest *request = [[QWeiboRequest alloc] init];
    QOauthKey *oauthKey = [self getOauthKey];
	NSString *retString = [request syncRequestWithUrl:urlString 
                                           httpMethod:@"POST" 
                                             oauthKey:oauthKey 
                                           parameters:nil 
                                                files:nil];
	Comment * result = [JsonStatusParser parseToComment:retString];
	
	[urlString release];
	[result autorelease];
	[retString release];
	return result;								
}



@end
